const { createApp } = Vue

createApp({
    data() {
        return {
            currentView: 'profile',
            appointmentFilter: 'all',
            defaultAvatars: {
                male: 'images/avatar-male.svg',
                female: 'images/avatar-female.svg'
            },
            passwordForm: {
                oldPassword: '',
                newPassword: '',
                confirmPassword: ''
            },
            user: {
                name: '',
                phone: '',
                email: '',
                gender: 'male',
                birthday: '',
                bio: ''
            },
            appointments: [],
            filteredAppointments: [],
            loading: false,
            error: null,
            therapistAvatars: [
                '/images/therapist1.svg',
                '/images/therapist2.svg',
                '/images/therapist-male.svg',
                '/images/therapist-female.svg'
            ],
            pagination: {
                currentPage: 1,
                pageSize: 5, // 每页显示5条记录
                total: 0
            },
            displayedAppointments: [] // 当前页显示的预约数据
        }
    },
    computed: {
        filteredAppointments() {
            if (this.appointmentFilter === 'all') {
                return this.appointments;
            }
            return this.appointments.filter(appointment =>
                appointment.status === this.appointmentFilter
            );
        },
        userAvatar() {
            return this.defaultAvatars[this.user.gender] || this.defaultAvatars.male;
        },
        totalPages() {
            return Math.ceil(this.pagination.total / this.pagination.pageSize);
        }
    },
    watch: {
        'user.gender': function (newGender) {
            console.log('性别改变:', newGender);
        },
        appointmentFilter: {
            handler: 'handleFilterChange',
            immediate: true
        }
    },
    methods: {
        goToPage(page) {
            switch (page) {
                case 'index':
                    window.location.href = 'index.html';
                    break;
                case 'consultation':
                    window.location.href = 'consultation.html';
                    break;
                case 'therapist':
                    window.location.href = 'therapist.html';
                    break;
                case 'about':
                    window.location.href = 'about.html';
                    break;
                case 'user-center':
                    window.location.href = 'user-center.html';
                    break;
                case 'login':
                    window.location.href = 'login.html';
                    break;
            }
        },
        switchView(view) {
            if (['profile', 'appointments', 'settings'].includes(view)) {
                this.currentView = view;
            }
        },
        saveProfile() {
            if (!this.validateForm()) {
                return;
            }

            if (!confirm('确定要保存修改吗？')) {
                return;
            }

            // 构造请求数据，只使用日期部分
            const profileData = {
                name: this.user.name,
                phone: this.user.phone,
                email: this.user.email,
                gender: this.user.gender === 'male' ? '男' : '女',
                birthday: this.user.birthday || null,  // 直接使用 YYYY-MM-DD 格式
                bio: this.user.bio
            };

            console.log('发送保存请求:', profileData);

            // 发送请求到后端
            axios({
                method: 'put',
                url: '/api/user/profile',
                data: profileData,
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'Authorization': localStorage.getItem('token')
                }
            })
                .then(response => {
                    console.log('保存响应:', response.data);
                    if (response.data.code === 200) {
                        alert('个人信息保存成功');
                    } else {
                        alert(response.data.message || '保存失败');
                    }
                })
                .catch(error => {
                    console.error('保存失败:', error);
                    alert('网络错误，请稍后重试');
                });
        },
        validateForm() {
            if (!this.user.name.trim()) {
                alert('请输入姓名');
                return false;
            }
            if (!this.user.phone.trim()) {
                alert('请输入手机号码');
                return false;
            }
            const phoneRegex = /^1[3-9]\d{9}$/;
            if (!phoneRegex.test(this.user.phone)) {
                alert('请输入正确的手机号码');
                return false;
            }
            if (!this.user.email.trim()) {
                alert('请输入电子邮箱');
                return false;
            }
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(this.user.email)) {
                alert('请输入正确的电子邮箱');
                return false;
            }
            if (!this.user.birthday) {
                alert('请选择出生日期');
                return false;
            }
            if (!this.user.bio.trim()) {
                alert('请输入个人简介');
                return false;
            }
            return true;
        },
        async fetchAppointments() {
            this.loading = true;
            this.error = null;

            try {
                const response = await axios.get('/api/appointments/user', {
                    headers: {
                        'Authorization': localStorage.getItem('token')
                    }
                });

                if (response.data.code === "200") {
                    // 保存所有预约记录
                    this.appointments = response.data.data.map(appointment => ({
                        ...appointment,
                        therapistAvatar: this.getRandomAvatar()
                    }));
                    // 执行筛选
                    this.filterAppointments();
                } else if (response.data.code === "401") {
                    localStorage.removeItem('token');
                    window.location.href = 'login.html';
                } else {
                    throw new Error(response.data.message || '获取预约记录失败');
                }
            } catch (error) {
                console.error('获取预约记录失败:', error);
                if (error.response?.status === 401) {
                    localStorage.removeItem('token');
                    window.location.href = 'login.html';
                } else {
                    this.error = '获取预约记录失败，请稍后重试';
                }
            } finally {
                this.loading = false;
            }
        },
        async cancelAppointment(appointmentId) {
            if (!confirm('确定要取消这个预约吗？')) {
                return;
            }

            try {
                const response = await axios.post(`/api/appointments/${appointmentId}/cancel`, null, {
                    headers: {
                        'Authorization': localStorage.getItem('token')
                    }
                });

                if (response.data.code === "200") {
                    alert('预约已取消');
                    // 重新加载预约记录
                    this.fetchAppointments();
                } else if (response.data.code === "401") {
                    localStorage.removeItem('token');
                    window.location.href = 'login.html';
                } else {
                    throw new Error(response.data.message || '取消预约失败');
                }
            } catch (error) {
                console.error('取消预约失败:', error);
                if (error.response?.status === 401) {
                    localStorage.removeItem('token');
                    window.location.href = 'login.html';
                } else {
                    alert('取消预约失败，请稍后重试');
                }
            }
        },
        changePassword() {
            if (!this.validatePasswordForm()) {
                return;
            }
            // 这里应该调用后端API修改密码
            console.log('修改密码：', this.passwordForm);
            alert('密码修改成功');
            this.passwordForm = {
                oldPassword: '',
                newPassword: '',
                confirmPassword: ''
            };
        },
        validatePasswordForm() {
            if (!this.passwordForm.oldPassword) {
                alert('请输入当前密码');
                return false;
            }
            if (!this.passwordForm.newPassword) {
                alert('请输入新密码');
                return false;
            }
            if (this.passwordForm.newPassword.length < 6) {
                alert('新密码长度不能少于6位');
                return false;
            }
            if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
                alert('两次输入的密码不一致');
                return false;
            }
            return true;
        },
        async getUserProfile() {
            try {
                console.log('开始获取用户信息');
                const response = await axios({
                    method: 'get',
                    url: '/api/user/info',
                    headers: {
                        'Authorization': localStorage.getItem('token')
                    }
                });

                console.log('获取用户信息响应:', response.data);
                // 检查code的类型，因为后端返回的是字符串"200"
                if (response.data.code === "200" || response.data.code === 200) {
                    // 转换性别格式
                    const userData = response.data.data;
                    userData.gender = userData.gender === '男' ? 'male' : 'female';

                    // 处理 null 值
                    this.user = {
                        name: userData.name || '',
                        phone: userData.phone || '',
                        email: userData.email || '',
                        gender: userData.gender,
                        birthday: userData.birthday || '',
                        bio: userData.bio || ''
                    };
                    console.log('用户信息更新成功:', this.user);
                } else if (response.data.code === "401" || response.data.code === 401) {
                    console.log('token失效');
                    localStorage.removeItem('token');
                    window.location.href = 'login.html';
                } else {
                    console.error('获取用户信息失败:', response.data);
                    alert(response.data.message || '获取用户信息失败');
                }
            } catch (error) {
                console.error('获取用户信息请求失败:', error);
                console.error('错误详情:', error.response?.data);
                if (error.response?.status === 401) {
                    localStorage.removeItem('token');
                    window.location.href = 'login.html';
                } else {
                    alert('网络错误，请稍后重试');
                }
            }
        },
        getRandomAvatar() {
            const index = Math.floor(Math.random() * this.therapistAvatars.length);
            return this.therapistAvatars[index];
        },
        filterAppointments() {
            if (this.appointmentFilter === 'all') {
                this.filteredAppointments = this.appointments;
            } else {
                this.filteredAppointments = this.appointments.filter(
                    appointment => appointment.status === this.appointmentFilter
                );
            }
            // 重置页码并更新分页
            this.pagination.currentPage = 1;
            this.handlePagination();
        },
        handleFilterChange() {
            this.filterAppointments();
        },
        handlePagination() {
            const start = (this.pagination.currentPage - 1) * this.pagination.pageSize;
            const end = start + this.pagination.pageSize;
            // 使用过滤后的预约数据进行分页
            this.displayedAppointments = this.filteredAppointments.slice(start, end);
            this.pagination.total = this.filteredAppointments.length;
        },
        changePage(page) {
            this.pagination.currentPage = page;
            this.handlePagination();
        },
        async changePassword() {
            if (!this.validatePasswordForm()) {
                return;
            }

            try {
                const response = await axios({
                    method: 'put',
                    url: '/api/user/password',
                    data: {
                        oldPassword: this.passwordForm.oldPassword,
                        newPassword: this.passwordForm.newPassword
                    },
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': localStorage.getItem('token')
                    }
                });

                if (response.data.code === "200") {
                    alert('密码修改成功，请重新登录');
                    // 清除token并跳转到登录页
                    localStorage.removeItem('token');
                    window.location.href = 'login.html';
                } else {
                    throw new Error(response.data.message || '修改密码失败');
                }
            } catch (error) {
                console.error('修改密码失败:', error);
                alert(error.response?.data?.message || error.message || '修改密码失败，请稍后重试');
            }
        },
        resetPasswordForm() {
            this.passwordForm = {
                oldPassword: '',
                newPassword: '',
                confirmPassword: ''
            };
        }
    },
    created() {
        // 页面创建时获取用户信息
        this.getUserProfile();
        this.fetchAppointments();
    }
}).mount('#app') 